package com.ywy.utils;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Xml工具类
 */
public class XmlUtil {
    /**
     * 生成xml
     *
     * @return
     */
    public static String genXml(Map<String, Object> map) throws Exception {
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>");
        for (String k : map.keySet()) {
            Object value = map.get(k);
            sb.append("<" + k + ">" + value + "</" + k + ">");
        }
        sb.append("</xml>");
        return new String(sb.toString().getBytes(), "ISO8859-1");
    }

    /**
     * 解析xml,返回第一级元素键值对。如果第一级元素有子节点，则此节点的值是子节点的xml数据。
     *
     * @param xmlStr
     * @return
     * @throws Exception
     */
    public static Map parseToMap(String xmlStr) throws Exception {
        xmlStr = xmlStr.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");
        if (null == xmlStr || "".equals(xmlStr)) {
            return null;
        }

        Map<String, Object> map = new HashMap<>();
        Document doc = DocumentHelper.parseText(xmlStr);
        Element root = doc.getRootElement();
        List list = root.elements();
        Iterator it = list.iterator();
        while (it.hasNext()) {
            Element e = (Element) it.next();
            map.put(e.getName(), e.getText());
        }

        return map;
    }

    public static String getElementValue(InputStream in, String key) throws Exception {
        SAXReader reader = new SAXReader();
        Document document = reader.read(in);
        Element root = document.getRootElement();
        List<Element> childElements = root.elements();
        for (Element child : childElements) {
            if (key.equals(child.getName())) {
                return child.getStringValue();
            }
        }
        return null;
    }
}
